package com.max.back.common.excel;

import com.max.back.demo.entity.Drug;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class PoiUtils {

    /**
     * Excel 解析成数据集合
     *
     * @return
     */
    public static List<Drug> excel2Employee(MultipartFile file) {
        List<Drug> list = new ArrayList<>();
        Drug employee = null;
        try {
            //1. 创建一个 workbook 对象
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
            //2. 获取 workbook 中表单的数量
            int numberOfSheets = workbook.getNumberOfSheets();
            for (int i = 0; i < numberOfSheets; i++) {
                //3. 获取表单
                XSSFSheet sheet = workbook.getSheetAt(i);
                //4. 获取表单中的行数
                int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
                for (int j = 0; j < physicalNumberOfRows; j++) {
                    //5. 跳过标题行
                    if (j == 0) {
                        continue;//跳过标题行
                    }
                    //6. 获取行
                    XSSFRow row = sheet.getRow(j);
                    if (row == null) {
                        continue;//防止数据中间有空行
                    }
                    //7. 获取列数
                    int physicalNumberOfCells = row.getPhysicalNumberOfCells();
                    employee = new Drug();
                    employee.setNumber(row.getCell(0).getStringCellValue());
                    employee.setName(row.getCell(1).getStringCellValue());
                    employee.setSpci(row.getCell(2).getStringCellValue());
                    employee.setUnit(row.getCell(3).getStringCellValue());
                    employee.setPrice((float) row.getCell(4).getNumericCellValue());
                    employee.setType1(row.getCell(5).getStringCellValue());
                    employee.setType2(row.getCell(6).getStringCellValue());
                    // 最后将解析后的数据添加到员工集合中
                    list.add(employee);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
